// 游戏控制器，控制其他所有类
import Food from "./Food";
import ScorePanel from "./ScorePanel";
import Snake from "./Snake";
class GameControl {
    //定义三个属性
    //🐍
    snake: Snake
    //食物
    food: Food
    //记分牌
    scorePanel: ScorePanel
    //存储按键
    direction: string = 'Right'
    //记录游戏是否结束
    isLive = true
    //获取按键
    btn: HTMLCollection

    constructor() {
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel()
        this.btn = document.getElementById('BUT')!.getElementsByTagName('div')
        this.init();
        // console.log(this.btn);


    }

    //游戏的初始化，调用开始游戏
    init() {
        //绑定键盘的按键
        //addEventListener() 方法用于向指定元素添加事件句柄。
        document.addEventListener('keydown', this.keyDownHandler.bind(this))
        this.btn[0].addEventListener('click', () => {
            this.direction = 'ArrowUp'
        })
        this.btn[1].addEventListener('click', () => {
            this.direction = 'ArrowRight'
        })
        this.btn[2].addEventListener('click', () => {
            this.direction = 'ArrowLeft'
        })
        this.btn[3].addEventListener('click', () => {
            this.direction = 'ArrowDown'
        })
        //调用移动方法
        this.run()
    }
    //创建键盘相应函数
    // KeyboardEvent 对象描述了用户与键盘的交互。每个事件都描述了用户与一个按键（或一个按键和修饰键的组合）的单个交互；事件类型keydown， keypress 与 keyup 用于识别不同的键盘活动类型。
    keyDownHandler(event: KeyboardEvent) {
        // event.key获取用户的按键 返回字符串
        this.direction = event.key

        // ArrowUp
        // ArrowDown
        // ArrowLeft
        // ArrowRight
    }
    //创建蛇移动的方法
    run() {

        //获取蛇现在的坐标
        let X = this.snake.X
        let Y = this.snake.Y
        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y -= 10
                break;

            case "ArrowDown":
            case "Down":
                Y += 10
                break;

            case "ArrowLeft":
            case "Left":
                X -= 10
                break;

            case "ArrowRight":
            case "Right":
                X += 10
                break;
        }

        //检查🐍是否吃到食物
        this.checkEat(X, Y)

        //修改值
        try {
            this.snake.X = X
            this.snake.Y = Y
        } catch (e: any) {
            //接收异常，弹出提示框
            alert(e.message + 'GameOver')
            this.isLive = false
            this.snake.X = 0
            this.snake.Y = 0
            setTimeout(() => {
                alert('点击重新开始游戏')
                location.reload();
            }, 500);
        }


        // 开启定时器
        this.isLive && setTimeout(this.run.bind(this), 450 - (this.scorePanel.level - 1) * 10)
    }

    //🐍是否吃到食物
    checkEat(X: number, Y: number) {
        if (X === this.food.X && Y === this.food.Y) {
            this.food.change()
            this.snake.addBody()
            this.scorePanel.addScore()
        }

    }


}
export default GameControl